<template>
  <div class="appointment-schedule-page">
    <!-- 顶部导航栏 -->
    <van-nav-bar left-arrow @click-left="onBack" :border="false">
      <template #title>
        <div class="department-title" @click="showDepartmentSelector">
          {{ departmentName }}
          <van-icon name="arrow-down" size="14" class="dropdown-icon" />
        </div>
      </template>
      <template #right>
        <van-icon name="ellipsis" size="18" class="nav-icon" />
        <van-icon name="eye" size="18" class="nav-icon ml-3" />
      </template>
    </van-nav-bar>

    <!-- 页面内容 -->
    <div class="page-content">
      <!-- 日期选择器 -->
      <div class="date-selector">
        <div class="date-list" ref="dateListRef">
          <div 
            v-for="(date, index) in dateList" 
            :key="index"
            class="date-item"
            :class="{ active: selectedDateIndex === index }"
            @click="selectDate(index)"
          >
            <div class="day-name">{{ date.dayName }}</div>
            <div class="day-number">{{ date.dayNumber }}</div>
          </div>
        </div>
      </div>

      <!-- 医生列表 -->
      <div class="doctors-section">
        <div class="section-title">坐诊医生</div>
        <div class="doctors-list">
          <div 
            v-for="doctor in doctorsList" 
            :key="doctor.doctorId"
            class="doctor-card"
            @click="selectDoctor(doctor)"
          >
            <div class="doctor-avatar">
              <img :src="doctor.avatar || '/default-avatar.png'" :alt="doctor.doctorName" />
            </div>
            <div class="doctor-info">
              <div class="doctor-name">{{ doctor.doctorName }}</div>
              <div class="doctor-title">{{ doctor.title }}</div>
              <div class="doctor-specialty">{{ doctor.specialty }}</div>
              <div class="consultation-fee">¥{{ doctor.consultationFee }}</div>
            </div>
            <div class="availability">
              <van-button 
                v-if="doctor.remaining > 0"
                type="primary" 
                size="small"
                :disabled="doctor.remaining === 0"
                @click.stop="selectDoctor(doctor)"
              >
                剩余 {{ doctor.remaining }}
              </van-button>
              <van-button 
                v-else
                type="default" 
                size="small"
                disabled
              >
                约满
              </van-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 科室选择弹窗 -->
    <van-popup v-model:show="showDepartmentPopup" position="bottom" :style="{ height: '60%' }">
      <div class="department-popup">
        <div class="popup-header">
          <span class="popup-title">选择科室</span>
          <van-icon name="cross" @click="showDepartmentPopup = false" />
        </div>
        <div class="department-list">
          <div 
            v-for="dept in departmentList" 
            :key="dept.departmentId"
            class="department-item"
            @click="selectDepartment(dept)"
          >
            {{ dept.departmentName }}
          </div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { api } from '../../api'

const router = useRouter()
const route = useRoute()

// 响应式数据
const departmentName = ref('消化内科')
const selectedDateIndex = ref(0)
const doctorsList = ref<any[]>([])
const departmentList = ref<any[]>([])
const showDepartmentPopup = ref(false)
const dateListRef = ref<HTMLElement>()

// 日期列表
const dateList = computed(() => {
  const dates = []
  const today = new Date()
  
  for (let i = 0; i < 7; i++) {
    const date = new Date(today)
    date.setDate(today.getDate() + i)
    
    const dayNames = ['今日', '周六', '周日', '周一', '周二', '周三', '周四']
    const dayName = i === 0 ? '今日' : dayNames[date.getDay()]
    
    dates.push({
      dayName,
      dayNumber: date.getDate(),
      fullDate: date.toISOString().split('T')[0]
    })
  }
  
  return dates
})

// 返回上一页
const onBack = () => {
  router.back()
}

// 选择日期
const selectDate = (index: number) => {
  selectedDateIndex.value = index
  loadDoctorsList()
}

// 选择医生
const selectDoctor = (doctor: any) => {
  if (doctor.remaining <= 0) return
  
  // 获取路由参数中的患者信息（如果有的话）
  const patientInfo = {
    patientId: route.query.patientId,
    name: route.query.name,
    relationship: route.query.relationship,
    idCardType: route.query.idCardType,
    idCardNum: route.query.idCardNum,
    medicalCard: route.query.medicalCard,
    phone: route.query.phone,
    address: route.query.address
  }
  
  // 跳转到预约确认页面（AppointAddFan）
  router.push({
    name: 'select-patient-fan',
    query: {
      // 传递患者信息（如果有的话）
      ...patientInfo,
      // 传递科室信息
      departmentId: route.params.departmentId,
      departmentName: departmentName.value,
      mainDepartmentId: route.query.mainDepartmentId,
      mainDepartmentName: route.query.mainDepartmentName,
      // 传递医生信息
      doctorId: doctor.doctorId,
      doctorName: doctor.doctorName,
      title: doctor.title,
      consultationFee: doctor.consultationFee,
      // 传递预约日期信息
      appointmentDate: dateList.value[selectedDateIndex.value].fullDate,
      // 如果有预约ID，也传递过去用于反填
      appointmentId: route.query.appointmentId
    }
  })
}

// 显示科室选择器
const showDepartmentSelector = () => {
  showDepartmentPopup.value = true
}

// 选择科室
const selectDepartment = (dept: any) => {
  departmentName.value = dept.departmentName
  showDepartmentPopup.value = false
  loadDoctorsList()
}

// 加载医生列表
const loadDoctorsList = async () => {
  try {
    // 根据科室ID和日期加载医生数据
    const departmentId = route.params.departmentId
    const selectedDate = dateList.value[selectedDateIndex.value]?.fullDate
    
    if (!departmentId) {
      console.warn('缺少科室ID参数')
      return
    }
    
    // 这里应该调用真实的API获取医生列表
    // const response = await api.getDoctorsByDepartment(departmentId, selectedDate)
    
    // 暂时使用模拟数据
    const mockDoctors = [
      {
        doctorId: 1,
        doctorName: '张三沣',
        title: '主任医师',
        specialty: '消化系统的疾病的治疗,擅长肝胆疾病的治疗',
        consultationFee: 60,
        remaining: 23,
        avatar: ''
      },
      {
        doctorId: 2,
        doctorName: '李四涛',
        title: '主任医师',
        specialty: '消化系统的疾病的治疗,擅长肝胆疾病的治疗',
        consultationFee: 50,
        remaining: 0,
        avatar: ''
      },
      {
        doctorId: 3,
        doctorName: '王五五',
        title: '主任医师',
        specialty: '消化系统的疾病的治疗,擅长肝胆疾病的治疗',
        consultationFee: 80,
        remaining: 20,
        avatar: ''
      },
      {
        doctorId: 4,
        doctorName: '赵六鎏',
        title: '主任医师',
        specialty: '消化系统的疾病的治疗,擅长肝胆疾病的治疗',
        consultationFee: 40,
        remaining: 19,
        avatar: ''
      }
    ]
    
    doctorsList.value = mockDoctors
  } catch (error) {
    console.error('加载医生列表失败:', error)
  }
}

// 加载科室列表
const loadDepartmentList = async () => {
  try {
    const response = await api.getDepartments()
    if (response.code === 200) {
      // 处理不同的响应格式
      if (Array.isArray(response.data)) {
        departmentList.value = response.data
      } else if (response.data && response.data.list) {
        departmentList.value = response.data.list
      } else {
        departmentList.value = []
      }
    }
  } catch (error) {
    console.error('加载科室列表失败:', error)
  }
}

// 获取预约详情数据（用于反填科室信息）
const loadAppointmentData = async () => {
  try {
    // 优先使用从Department页面传递过来的科室信息
    if (route.query.departmentName) {
      departmentName.value = route.query.departmentName as string
      console.log('使用传递的科室信息:', route.query.departmentName)
      return
    }
    
    // 如果没有传递科室信息，则尝试从预约数据中获取
    const appointmentId = route.query.appointmentId || 1
    console.log('正在获取预约数据，AppointmentId:', appointmentId)
    
    const response = await fetch(`http://localhost:5250/api/Appoint/AppointFan?AppointmentId=${appointmentId}`)
    const data = await response.json()
    
    console.log('预约数据响应:', data)
    
    if (data.code === 600 && data.data && data.data.length > 0) {
      const appointmentData = data.data[0]
      // 反填科室信息
      if (appointmentData.department) {
        departmentName.value = appointmentData.department
        console.log('成功反填科室信息:', appointmentData.department)
      }
    } else {
      console.log('未找到预约数据，使用默认科室名称')
    }
  } catch (error) {
    console.error('获取预约数据失败:', error)
    // 如果获取失败，使用默认科室名称
    departmentName.value = '消化内科'
  }
}

// 页面加载时初始化
onMounted(async () => {
  await loadAppointmentData()
  await loadDepartmentList()
  await loadDoctorsList()
  
  // 设置默认选中第一个日期
  selectedDateIndex.value = 0
})

// 监听路由参数变化
watch(() => route.params.departmentId, (newId) => {
  if (newId) {
    loadDoctorsList()
  }
})
</script>

<style scoped>
.appointment-schedule-page {
  min-height: 100vh;
  background-color: #f7f8fa;
}

/* 导航栏样式 */
:deep(.van-nav-bar) {
  background-color: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

:deep(.van-nav-bar__title) {
  font-size: 17px;
  font-weight: 600;
  color: #323233;
}

.department-title {
  display: flex;
  align-items: center;
  gap: 4px;
  cursor: pointer;
  transition: color 0.2s;
}

.department-title:hover {
  color: #1989fa;
}

.dropdown-icon {
  transition: transform 0.2s;
}

.department-title:hover .dropdown-icon {
  transform: rotate(180deg);
}

.nav-icon {
  color: #323233;
}

.ml-3 {
  margin-left: 12px;
}

.page-content {
  background-color: #fff;
}

/* 日期选择器样式 */
.date-selector {
  padding: 16px;
  background-color: #fff;
  border-bottom: 1px solid #f7f8fa;
}

.date-list {
  display: flex;
  gap: 16px;
  overflow-x: auto;
  padding-bottom: 8px;
}

.date-item {
  min-width: 60px;
  text-align: center;
  padding: 12px 8px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
  background-color: #f7f8fa;
}

.date-item.active {
  background-color: #1989fa;
  color: #fff;
}

.day-name {
  font-size: 12px;
  color: #969799;
  margin-bottom: 4px;
}

.date-item.active .day-name {
  color: #fff;
}

.day-number {
  font-size: 16px;
  font-weight: 600;
  color: #323233;
}

.date-item.active .day-number {
  color: #fff;
}

/* 医生列表样式 */
.doctors-section {
  padding: 16px;
  background-color: #f7f8fa;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #323233;
  margin-bottom: 16px;
}

.doctors-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.doctor-card {
  display: flex;
  align-items: center;
  background-color: #fff;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  cursor: pointer;
  transition: all 0.2s;
}

.doctor-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.doctor-avatar {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  background-color: #f7f8fa;
  margin-right: 16px;
  overflow: hidden;
}

.doctor-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.doctor-info {
  flex: 1;
}

.doctor-name {
  font-size: 16px;
  font-weight: 600;
  color: #323233;
  margin-bottom: 4px;
}

.doctor-title {
  font-size: 14px;
  color: #1989fa;
  margin-bottom: 4px;
}

.doctor-specialty {
  font-size: 12px;
  color: #969799;
  line-height: 1.4;
  margin-bottom: 8px;
}

.consultation-fee {
  font-size: 14px;
  font-weight: 600;
  color: #ff6b35;
}

.availability {
  margin-left: 12px;
}

/* 科室选择弹窗样式 */
.department-popup {
  padding: 16px;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 16px;
  border-bottom: 1px solid #f7f8fa;
  margin-bottom: 16px;
}

.popup-title {
  font-size: 16px;
  font-weight: 600;
  color: #323233;
}

.department-list {
  max-height: 400px;
  overflow-y: auto;
}

.department-item {
  padding: 16px;
  border-bottom: 1px solid #f7f8fa;
  cursor: pointer;
  transition: background-color 0.2s;
}

.department-item:hover {
  background-color: #f7f8fa;
}

.department-item:last-child {
  border-bottom: none;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .date-item {
    min-width: 50px;
    padding: 10px 6px;
  }
  
  .day-number {
    font-size: 14px;
  }
  
  .doctor-card {
    padding: 12px;
  }
  
  .doctor-avatar {
    width: 50px;
    height: 50px;
    margin-right: 12px;
  }
  
  .doctor-name {
    font-size: 15px;
  }
  
  .doctor-title {
    font-size: 13px;
  }
  
  .doctor-specialty {
    font-size: 11px;
  }
}

/* iPhone 样式适配 */
@media (max-width: 414px) {
  .date-selector {
    padding: 12px;
  }
  
  .date-list {
    gap: 12px;
  }
  
  .date-item {
    min-width: 45px;
    padding: 8px 4px;
  }
  
  .day-name {
    font-size: 11px;
  }
  
  .day-number {
    font-size: 13px;
  }
  
  .doctors-section {
    padding: 12px;
  }
  
  .doctor-card {
    padding: 10px;
  }
  
  .doctor-avatar {
    width: 45px;
    height: 45px;
    margin-right: 10px;
  }
}
</style>
